<template>
  <view>
    <view class="subsection-box">
      <view class="subsection-box-view" v-for="(item, index) in list" :key="index"
            :class="value === item.value ? 'highlight' : ''" @click="handleClick(item)">
        <view>{{ item.name }}</view>
        <view >
<!--          <u-icon name="arrow-down-fill" class="u-add-btn" size="12"></u-icon>-->
        </view>
      </view>
    </view>
    <popup v-model="visible" mode="bottom" height="70%">
      <view style="width: 100%; height: 100%;display: flex;flex-direction: column;color: #000">
        <view class="title">
          <view @click="visible = false">取消</view>
          <view style="flex: 1"></view>
          <view style="color: #007FFF" @click="handleAffirm">确认</view>
        </view>
        <view style="flex: 1">
          <picker-view :indicator-style="indicatorStyle" :value.sync="dateValue"
                       class="picker-view">
            <picker-view-column>
              <view class="item" :style="{lineHeight: height}" v-for="(item,index) in years" :key="index">{{ item }}年</view>
            </picker-view-column>
            <picker-view-column v-if="value === 'month'">
              <view class="item" :style="{lineHeight: height}" v-for="(item,index) in months" :key="index">{{ item }}月</view>
            </picker-view-column>
            <picker-view-column v-if="value === 'week'">
              <view class="item" :style="{lineHeight: height}" v-for="(item,index) in weeks" :key="index">{{ item.key }}周 {{item.name}}</view>
            </picker-view-column>
            <picker-view-column v-if="value === 'quarter'">
              <view class="item" :style="{lineHeight: height}" v-for="(item,index) in quarters" :key="index">{{ item.name }}</view>
            </picker-view-column>
          </picker-view>
        </view>
      </view>
    </popup>
  </view>
</template>

<script>
import dayjs from '../../dayjs';
import Popup from "./popup";
const weekOfYear = require('../../dayjs/plugin/weekOfYear');
const quarterOfYear = require('../../dayjs/plugin/quarterOfYear');

const getWeekNumber = function(src) {
  if (!isDate(src)) return null;
  const date = new Date(src.getTime());
  date.setHours(0, 0, 0, 0);
  // Thursday in current week decides the year.
  date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
  // January 4 is always in week 1.
  const week1 = new Date(date.getFullYear(), 0, 4);
  // Adjust to Thursday in week 1 and count number of weeks from date to week 1.
  // Rounding should be fine for Daylight Saving Time. Its shift should never be more than 12 hours.
  return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
};

const isDate = function(date) {
  if (date === null || date === undefined) return false;
  if (isNaN(new Date(date).getTime())) return false;
  if (Array.isArray(date)) return false; // deal with `new Date([ new Date() ]) -> new Date()`
  return true;
};

/**
 * @describe只有高亮的点击箭头才会弹出选择
 * @type {String} @describe 默认哪一个高亮;
 * @height {String} @describe 上拉弹框行高度;
 * @listLabel {String}  @describe 显示那几个类型默认全部显示;
 * @firstDay {Number}  @describe 默认0周日为一周的第一天，可选1周一为一周的第一天;
 * */
export default {
  name: 'DateScope',
  props: {
	firstDay: {
	  type: Number,
	  default: 0
	},
    value: {
      type: String,
      default: ''
    },
    height: {
      type: String,
      default: '100rpx'
    },
    listLabel: {
      type: String,
      default: '周,月,季度,年'
    }
  },
  data() {
    return {
      dateValue: [],
      visible: false
    };
  },
  components: {
    Popup
  },
  computed: {
    list() {
      const list = [];
      this.listLabel.split(',').forEach(item => {
        if (item === '周') {
          list.push({name: '周', value: 'week'});
        }
        if (item === '月') {
          list.push({name: '月', value: 'month'});
        }
        if (item === '季度') {
          list.push({name: '季度', value: 'quarter'});
        }
        if (item === '年') {
          list.push({name: '年', value: 'year'});
        }
      });
      return list;
    },
    indicatorStyle() {
      return `height: ${this.height};`;
    },
    years() {
      const years = [];
      const date = new Date();
      for (let i = 1990; i <= date.getFullYear() + 10; i++) {
        years.push(i);
      }
      return years;
    },
    months() {
      const months = [];
      for (let i = 1; i <= 12; i++) {
        months.push(i)
      }
      return months;
    },
    weeks() {
      const list = [];
      let i = 1;
      const year = this.years[this.dateValue[0]];
      // console.log('year', year);
      const d = new Date(year, 0, 1);
      while (d.getDay() != this.firstDay) { // 设置周日为第一天
        d.setDate(d.getDate() + 1);
      }
      if (d.getDate() > 4) {
        d.setDate(d.getDate() - 7);
      }
      const to = new Date(year + 1, 0, 1);
      for (const from = d; from < to; ) {
        const value = [];
        if (from.getMonth() === 11 && (from.getDate() + 3) > 31 && i > 52) {
          return list;
        }
        let name = (from.getMonth() + 1) + '月' + from.getDate() + '日 - ';
        value[0] = dayjs(from).format('YYYY-MM-DD');
        from.setDate(from.getDate() + 6);
        if (from < to) {
          name += (from.getMonth() + 1) + '月' + from.getDate() + '日';
          value[1] = dayjs(from).format('YYYY-MM-DD');
          from.setDate(from.getDate() + 1);
        } else {
          name += (to.getMonth() + 1) + '月' + from.getDate() + '日';
          value[1] = dayjs(new Date(to.getFullYear(), to.getMonth(), from.getDate())).format('YYYY-MM-DD');
        }
        list.push({
          key: i,
          name,
          value
        });
        i++;
      }
      return list;
    },
    quarters() {
      const year = this.years[this.dateValue[0]];
      return [
        {name: '第一季度', value: [`${year}-01-31`, `${year}-03-31`]},
        {name: '第二季度', value: [`${year}-04-30`, `${year}-06-30`]},
        {name: '第三季度', value: [`${year}-07-31`, `${year}-09-30`]},
        {name: '第四季度', value: [`${year}-10-31`, `${year}-12-31`]}
      ];
    }
  },
  watch: {
    dateValue: {
	  deep: true,
	  handler(newVlaue, value) {
		if(newVlaue[0] !== value[0]) {
		    this.dateValue[1] = 0;
		}
	  }
	},
    value: {
      immediate: true,
      handler(val) {
        const dateStr = '2020-01-05';
        // const dateStr = '2019-12-29';
        const date = new Date(dateStr);
        this.dateValue[0] = this.years.indexOf(date.getFullYear());
        if (val === 'month') {
          this.dateValue[1] = this.months.indexOf(date.getMonth() + 1);
        }
        if (val === 'week') {
          // const a = date.setDate(date.getDate() + 7);
          const a = new Date(dateStr);
          a.setDate(a.getDate() + 7)
          console.log('date.getDay()', date.getDay());
          console.log('a.getDate()', a.getDate());
          if (date.getMonth() === 0 && date.getDate() < 4 && date.getDay() > 3) {
            console.log('上一年的最后一周')
            this.years[this.dateValue[0]] = date.getFullYear() - 1;
            this.dateValue[1] = this.weeks.length - 1;
          } else if (date.getMonth() === 11 && a.getDate() - 3 && date.getDay() < 4) {
            console.log('下一年的第一周')
            this.years[this.dateValue[0]] = date.getFullYear() + 1;
            this.dateValue[1] = 0;
          } else {
            // dayjs.extend(weekOfYear);
            // this.dateValue[1] = dayjs(date).week() - 2;
            console.log('getWeekNumber(date)', getWeekNumber(date));
            this.dateValue[1] = getWeekNumber(date) - 1;
          }
          console.log(' this.dateValue[1]',  this.dateValue[1]);
        }
        if (val === 'quarter') {
          dayjs.extend(quarterOfYear);
          this.dateValue[1] = dayjs(date).quarter() - 1;
        }
        this.handleAffirm();
      }
    }
  },
  methods: {
    handleAffirm() {
      let data = [];
      if (this.value === 'month') {
        data[0] = this.years[this.dateValue[0]];
        data[1] = this.months[this.dateValue[1]];
        data = this.getMonth(data);
      }
      if (this.value === 'week') {
        data = this.weeks[this.dateValue[1]].value;
      }
      if (this.value === 'quarter') {
        data = this.quarters[this.dateValue[1]].value;
      }
      if (this.value === 'year') {
        const years = this.years[this.dateValue[0]];
        data = [`${years}-01-01`, `${years}-12-31`];
      }
      this.visible = false;
      this.$emit('change', data);
    },
    getMonth(data) {
      const arr = [1, 3, 5, 7, 8, 10, 12];
      const arr1 = [4, 6, 9, 11];
      const year = data[0];
      let month = data[1];
      let day;
      if (arr.indexOf(month) !== -1) {
        day = 31;
      }
      if (arr1.indexOf(month) !== -1) {
        day = 30;
      }
      if (month === 2) {
        if (year % 4 === 0) {
          day = 29;
        } else {
          day = 28;
        }
      }
      month = month < 10 ? '0' + month : month;
      return [`${year}-${month}-01`, `${year}-${month}-${day}`]
    },
    handleClick(item) {
      if (item.value !== this.value) {
		this.$emit('update:value', item.value)
		return;
	  }
      this.visible = true;
    }
  }
};
</script>

<style scoped lang="scss">
.subsection-box {
  //width: 100%;
  border: 1rpx solid #FFFFFF;
  border-radius: 8rpx;
  display: flex;

  .subsection-box-view {
    //flex: 1;
    line-height: 54rpx;
    display: flex;

    & > view {
      padding: 0 8rpx;
      text-align: center;
    }
  }

  .highlight {
    background: #fff;
    color: #007FFF;
  }
}

.picker-view {
  width: 100%;
  height: 100%;
  margin-top: 20rpx;
}

.item {
  align-items: center;
  justify-content: center;
  text-align: center;
}

.title {
  display: flex;
  //height: 100rpx;
  line-height: 40rpx;
  padding: 30rpx;
  border-bottom: 1rpx solid #E5EBEE;
}
</style>
